<template>
    <div class="histogram-container">
      <div id="histogram-chart" style="width: 100%; height: 400px;"></div>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import axios from 'axios';
  
  export default {
    name: 'Histogram',
    data() {
      return {
        costDistribution: []  // 用于存储后端返回的cost数据
      };
    },
    mounted() {
      this.fetchCostData();
    },
    methods: {
      // 获取后端接口的cost分布数据
      fetchCostData() {
        axios.get('http://localhost:9900/data/cost')
          .then(response => {
            this.costDistribution = response.data.data;
            this.initChart();  // 获取数据后初始化图表
          })
          .catch(error => {
            console.error("Error fetching cost distribution data:", error);
          });
      },
      // 初始化ECharts图表
      initChart() {
        const chartDom = document.getElementById('histogram-chart');
        const myChart = echarts.init(chartDom);
        
        // 找出最小的记录数，用作Y轴起始值
        const minValue = Math.min(...this.costDistribution.map(item => item.count));
  
        const option = {
          title: {
            text: '以太坊交易金额分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            name: 'Cost',
            data: this.costDistribution.map(item => item.cost)  // 横轴：cost值
          },
          yAxis: {
            type: 'value',
            name: '记录数',
            min: minValue - 1000  // 设置Y轴的最小值，减去一定数值以增强视觉差距
          },
          series: [
            {
              name: '记录数',
              type: 'bar',
              data: this.costDistribution.map(item => item.count),  // 纵轴：记录数
              itemStyle: {
                // 使用不同的颜色
                color: (params) => {
                  const colorList = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC', '#737373'];
                  return colorList[params.dataIndex % colorList.length];  // 不同柱子使用不同的颜色
                }
              },
              label: {
                show: true,  // 在柱子上方显示数值
                position: 'top',
                formatter: '{c}'  // 直接显示Y轴的数值
              }
            }
          ]
        };
        myChart.setOption(option);  // 设置图表选项并渲染
      }
    }
  };
  </script>
  
  <style scoped>
  .histogram-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  </style>
  